package com.ssm.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ssm.dao.IUserDao;
import com.ssm.model.User;
import com.ssm.unity.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by xieyingze on 2018/1/1.
 */
public class SpringInterceptor implements HandlerInterceptor {

    @Autowired
    IUserDao userDao;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle方法" + request.getParameter("user_phone"));

        try {
            String requestMethod = request.getParameter("request_method");
            //如果注册或登录接口
            if (requestMethod.equals("user/register") || requestMethod.equals("user/login")) {
                return true;
            }
            //user_uuid除了注册登录接口外,需要每个请求必须带上user_uuid
            User user = userDao.queryUserByUserPhone(request.getParameter("user_uuid"));
            //如果用户设备uuid跟数据库不一致
            if (user.getUser_device_imei().equals(request.getParameter("user_device_imei"))) {
                return true;
            } else {
                PrintWriter writer = response.getWriter();
                ResponseResult result = new ResponseResult();
                result.setCurrentVersion();
                result.setStatusCode("failure");
                result.setInvoking("0002");
                result.setMessage("你的账号已在其他设备登录");
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result", result);
                writer.println(jsonObject.toJSONString());
                return false;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle方法 : " + request.getParameter("user_phone"));
        System.out.println(request.getMethod());
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion方法");
    }
}
